
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Databases &#8212; Django 2.2.12.dev20200304094918 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="django-admin and manage.py" href="django-admin.html" />
    <link rel="prev" title="Cross Site Request Forgery protection" href="csrf.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 2.2.12.dev20200304094918 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="csrf.html" title="Cross Site Request Forgery protection">previous</a>
     |
    <a href="index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="django-admin.html" title="&lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;django-admin&lt;/span&gt;&lt;/code&gt; and &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;manage.py&lt;/span&gt;&lt;/code&gt;">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-databases">
            
  <div class="section" id="s-databases">
<span id="databases"></span><h1>Databases<a class="headerlink" href="#databases" title="Permalink to this headline">¶</a></h1>
<p>Django officially supports the following databases:</p>
<ul class="simple">
<li><a class="reference internal" href="#postgresql-notes"><span class="std std-ref">PostgreSQL</span></a></li>
<li><a class="reference internal" href="#mysql-notes"><span class="std std-ref">MySQL</span></a></li>
<li><a class="reference internal" href="#oracle-notes"><span class="std std-ref">Oracle</span></a></li>
<li><a class="reference internal" href="#sqlite-notes"><span class="std std-ref">SQLite</span></a></li>
</ul>
<p>There are also a number of <a class="reference internal" href="#third-party-notes"><span class="std std-ref">database backends provided by third parties</span></a>.</p>
<p>Django attempts to support as many features as possible on all database
backends. However, not all database backends are alike, and we’ve had to make
design decisions on which features to support and which assumptions we can make
safely.</p>
<p>This file describes some of the features that might be relevant to Django
usage. Of course, it is not intended as a replacement for server-specific
documentation or reference manuals.</p>
<div class="section" id="s-general-notes">
<span id="general-notes"></span><h2>General notes<a class="headerlink" href="#general-notes" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-persistent-connections">
<span id="s-persistent-database-connections"></span><span id="persistent-connections"></span><span id="persistent-database-connections"></span><h3>Persistent connections<a class="headerlink" href="#persistent-connections" title="Permalink to this headline">¶</a></h3>
<p>Persistent connections avoid the overhead of re-establishing a connection to
the database in each request. They’re controlled by the
<a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CONN_MAX_AGE</span></code></a> parameter which defines the maximum lifetime of a
connection. It can be set independently for each database.</p>
<p>The default value is <code class="docutils literal notranslate"><span class="pre">0</span></code>, preserving the historical behavior of closing the
database connection at the end of each request. To enable persistent
connections, set <a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CONN_MAX_AGE</span></code></a> to a positive number of seconds. For
unlimited persistent connections, set it to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="section" id="s-connection-management">
<span id="connection-management"></span><h4>Connection management<a class="headerlink" href="#connection-management" title="Permalink to this headline">¶</a></h4>
<p>Django opens a connection to the database when it first makes a database
query. It keeps this connection open and reuses it in subsequent requests.
Django closes the connection once it exceeds the maximum age defined by
<a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CONN_MAX_AGE</span></code></a> or when it isn’t usable any longer.</p>
<p>In detail, Django automatically opens a connection to the database whenever it
needs one and doesn’t have one already — either because this is the first
connection, or because the previous connection was closed.</p>
<p>At the beginning of each request, Django closes the connection if it has
reached its maximum age. If your database terminates idle connections after
some time, you should set <a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CONN_MAX_AGE</span></code></a> to a lower value, so that
Django doesn’t attempt to use a connection that has been terminated by the
database server. (This problem may only affect very low traffic sites.)</p>
<p>At the end of each request, Django closes the connection if it has reached its
maximum age or if it is in an unrecoverable error state. If any database
errors have occurred while processing the requests, Django checks whether the
connection still works, and closes it if it doesn’t. Thus, database errors
affect at most one request; if the connection becomes unusable, the next
request gets a fresh connection.</p>
</div>
<div class="section" id="s-caveats">
<span id="caveats"></span><h4>Caveats<a class="headerlink" href="#caveats" title="Permalink to this headline">¶</a></h4>
<p>Since each thread maintains its own connection, your database must support at
least as many simultaneous connections as you have worker threads.</p>
<p>Sometimes a database won’t be accessed by the majority of your views, for
example because it’s the database of an external system, or thanks to caching.
In such cases, you should set <a class="reference internal" href="settings.html#std:setting-CONN_MAX_AGE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CONN_MAX_AGE</span></code></a> to a low value or even
<code class="docutils literal notranslate"><span class="pre">0</span></code>, because it doesn’t make sense to maintain a connection that’s unlikely
to be reused. This will help keep the number of simultaneous connections to
this database small.</p>
<p>The development server creates a new thread for each request it handles,
negating the effect of persistent connections. Don’t enable them during
development.</p>
<p>When Django establishes a connection to the database, it sets up appropriate
parameters, depending on the backend being used. If you enable persistent
connections, this setup is no longer repeated every request. If you modify
parameters such as the connection’s isolation level or time zone, you should
either restore Django’s defaults at the end of each request, force an
appropriate value at the beginning of each request, or disable persistent
connections.</p>
</div>
</div>
<div class="section" id="s-encoding">
<span id="encoding"></span><h3>Encoding<a class="headerlink" href="#encoding" title="Permalink to this headline">¶</a></h3>
<p>Django assumes that all databases use UTF-8 encoding. Using other encodings may
result in unexpected behavior such as “value too long” errors from your
database for data that is valid in Django. See the database specific notes
below for information on how to set up your database correctly.</p>
</div>
</div>
<div class="section" id="s-postgresql-notes">
<span id="s-id1"></span><span id="postgresql-notes"></span><span id="id1"></span><h2>PostgreSQL notes<a class="headerlink" href="#postgresql-notes" title="Permalink to this headline">¶</a></h2>
<p>Django supports PostgreSQL 9.4 and higher. <a class="reference external" href="http://initd.org/psycopg/">psycopg2</a> 2.5.4 or higher is
required, though the latest release is recommended.</p>
<div class="section" id="s-postgresql-connection-settings">
<span id="postgresql-connection-settings"></span><h3>PostgreSQL connection settings<a class="headerlink" href="#postgresql-connection-settings" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference internal" href="settings.html#std:setting-HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">HOST</span></code></a> for details.</p>
</div>
<div class="section" id="s-optimizing-postgresql-s-configuration">
<span id="optimizing-postgresql-s-configuration"></span><h3>Optimizing PostgreSQL’s configuration<a class="headerlink" href="#optimizing-postgresql-s-configuration" title="Permalink to this headline">¶</a></h3>
<p>Django needs the following parameters for its database connections:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">client_encoding</span></code>: <code class="docutils literal notranslate"><span class="pre">'UTF8'</span></code>,</li>
<li><code class="docutils literal notranslate"><span class="pre">default_transaction_isolation</span></code>: <code class="docutils literal notranslate"><span class="pre">'read</span> <span class="pre">committed'</span></code> by default,
or the value set in the connection options (see below),</li>
<li><code class="docutils literal notranslate"><span class="pre">timezone</span></code>: <code class="docutils literal notranslate"><span class="pre">'UTC'</span></code> when <a class="reference internal" href="settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, value of
<a class="reference internal" href="settings.html#std:setting-TIME_ZONE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TIME_ZONE</span></code></a> otherwise.</li>
</ul>
<p>If these parameters already have the correct values, Django won’t set them for
every new connection, which improves performance slightly. You can configure
them directly in <code class="file docutils literal notranslate"><span class="pre">postgresql.conf</span></code> or more conveniently per database
user with <a class="reference external" href="https://www.postgresql.org/docs/current/sql-alterrole.html">ALTER ROLE</a>.</p>
<p>Django will work just fine without this optimization, but each new connection
will do some additional queries to set these parameters.</p>
</div>
<div class="section" id="s-isolation-level">
<span id="s-database-isolation-level"></span><span id="isolation-level"></span><span id="database-isolation-level"></span><h3>Isolation level<a class="headerlink" href="#isolation-level" title="Permalink to this headline">¶</a></h3>
<p>Like PostgreSQL itself, Django defaults to the <code class="docutils literal notranslate"><span class="pre">READ</span> <span class="pre">COMMITTED</span></code> <a class="reference external" href="https://www.postgresql.org/docs/current/transaction-iso.html">isolation
level</a>. If you need a higher isolation level such as <code class="docutils literal notranslate"><span class="pre">REPEATABLE</span> <span class="pre">READ</span></code> or
<code class="docutils literal notranslate"><span class="pre">SERIALIZABLE</span></code>, set it in the <a class="reference internal" href="settings.html#std:setting-OPTIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">OPTIONS</span></code></a> part of your database
configuration in <a class="reference internal" href="settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">psycopg2.extensions</span>

<span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="c1"># ...</span>
    <span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;isolation_level&#39;</span><span class="p">:</span> <span class="n">psycopg2</span><span class="o">.</span><span class="n">extensions</span><span class="o">.</span><span class="n">ISOLATION_LEVEL_SERIALIZABLE</span><span class="p">,</span>
    <span class="p">},</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Under higher isolation levels, your application should be prepared to
handle exceptions raised on serialization failures. This option is
designed for advanced uses.</p>
</div>
</div>
<div class="section" id="s-indexes-for-varchar-and-text-columns">
<span id="indexes-for-varchar-and-text-columns"></span><h3>Indexes for <code class="docutils literal notranslate"><span class="pre">varchar</span></code> and <code class="docutils literal notranslate"><span class="pre">text</span></code> columns<a class="headerlink" href="#indexes-for-varchar-and-text-columns" title="Permalink to this headline">¶</a></h3>
<p>When specifying <code class="docutils literal notranslate"><span class="pre">db_index=True</span></code> on your model fields, Django typically
outputs a single <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">INDEX</span></code> statement.  However, if the database type
for the field is either <code class="docutils literal notranslate"><span class="pre">varchar</span></code> or <code class="docutils literal notranslate"><span class="pre">text</span></code> (e.g., used by <code class="docutils literal notranslate"><span class="pre">CharField</span></code>,
<code class="docutils literal notranslate"><span class="pre">FileField</span></code>, and <code class="docutils literal notranslate"><span class="pre">TextField</span></code>), then Django will create
an additional index that uses an appropriate <a class="reference external" href="https://www.postgresql.org/docs/current/indexes-opclass.html">PostgreSQL operator class</a>
for the column.  The extra index is necessary to correctly perform
lookups that use the <code class="docutils literal notranslate"><span class="pre">LIKE</span></code> operator in their SQL, as is done with the
<code class="docutils literal notranslate"><span class="pre">contains</span></code> and <code class="docutils literal notranslate"><span class="pre">startswith</span></code> lookup types.</p>
</div>
<div class="section" id="s-migration-operation-for-adding-extensions">
<span id="migration-operation-for-adding-extensions"></span><h3>Migration operation for adding extensions<a class="headerlink" href="#migration-operation-for-adding-extensions" title="Permalink to this headline">¶</a></h3>
<p>If you need to add a PostgreSQL extension (like <code class="docutils literal notranslate"><span class="pre">hstore</span></code>, <code class="docutils literal notranslate"><span class="pre">postgis</span></code>, etc.)
using a migration, use the
<a class="reference internal" href="contrib/postgres/operations.html#django.contrib.postgres.operations.CreateExtension" title="django.contrib.postgres.operations.CreateExtension"><code class="xref py py-class docutils literal notranslate"><span class="pre">CreateExtension</span></code></a> operation.</p>
</div>
<div class="section" id="s-server-side-cursors">
<span id="s-postgresql-server-side-cursors"></span><span id="server-side-cursors"></span><span id="postgresql-server-side-cursors"></span><h3>Server-side cursors<a class="headerlink" href="#server-side-cursors" title="Permalink to this headline">¶</a></h3>
<p>When using <a class="reference internal" href="models/querysets.html#django.db.models.query.QuerySet.iterator" title="django.db.models.query.QuerySet.iterator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">QuerySet.iterator()</span></code></a>, Django opens a <a class="reference external" href="https://www.psycopg.org/docs/usage.html#server-side-cursors" title="(in Psycopg v2.8)"><span class="xref std std-ref">server-side
cursor</span></a>. By default, PostgreSQL assumes that
only the first 10% of the results of cursor queries will be fetched. The query
planner spends less time planning the query and starts returning results
faster, but this could diminish performance if more than 10% of the results are
retrieved. PostgreSQL’s assumptions on the number of rows retrieved for a
cursor query is controlled with the <a class="reference external" href="https://www.postgresql.org/docs/current/runtime-config-query.html#GUC-CURSOR-TUPLE-FRACTION">cursor_tuple_fraction</a> option.</p>
<div class="section" id="s-transaction-pooling-and-server-side-cursors">
<span id="s-transaction-pooling-server-side-cursors"></span><span id="transaction-pooling-and-server-side-cursors"></span><span id="transaction-pooling-server-side-cursors"></span><h4>Transaction pooling and server-side cursors<a class="headerlink" href="#transaction-pooling-and-server-side-cursors" title="Permalink to this headline">¶</a></h4>
<p>Using a connection pooler in transaction pooling mode (e.g. <a class="reference external" href="https://pgbouncer.github.io/">pgBouncer</a>)
requires disabling server-side cursors for that connection.</p>
<p>Server-side cursors are local to a connection and remain open at the end of a
transaction when <a class="reference internal" href="settings.html#std:setting-DATABASE-AUTOCOMMIT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTOCOMMIT</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>. A
subsequent transaction may attempt to fetch more results from a server-side
cursor. In transaction pooling mode, there’s no guarantee that subsequent
transactions will use the same connection. If a different connection is used,
an error is raised when the transaction references the server-side cursor,
because server-side cursors are only accessible in the connection in which they
were created.</p>
<p>One solution is to disable server-side cursors for a connection in
<a class="reference internal" href="settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a> by setting <a class="reference internal" href="settings.html#std:setting-DATABASE-DISABLE_SERVER_SIDE_CURSORS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DISABLE_SERVER_SIDE_CURSORS</span></code></a> to <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
<p>To benefit from server-side cursors in transaction pooling mode, you could set
up <a class="reference internal" href="../topics/db/multi-db.html"><span class="doc">another connection to the database</span></a> in order to
perform queries that use server-side cursors. This connection needs to either
be directly to the database or to a connection pooler in session pooling mode.</p>
<p>Another option is to wrap each <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> using server-side cursors in an
<a class="reference internal" href="../topics/db/transactions.html#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block, because it disables <code class="docutils literal notranslate"><span class="pre">autocommit</span></code>
for the duration of the transaction. This way, the server-side cursor will only
live for the duration of the transaction.</p>
</div>
</div>
<div class="section" id="s-manually-specifying-values-of-auto-incrementing-primary-keys">
<span id="s-manually-specified-autoincrement-pk"></span><span id="manually-specifying-values-of-auto-incrementing-primary-keys"></span><span id="manually-specified-autoincrement-pk"></span><h3>Manually-specifying values of auto-incrementing primary keys<a class="headerlink" href="#manually-specifying-values-of-auto-incrementing-primary-keys" title="Permalink to this headline">¶</a></h3>
<p>Django uses PostgreSQL’s <a class="reference external" href="https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-SERIAL">SERIAL data type</a> to store auto-incrementing primary
keys. A <code class="docutils literal notranslate"><span class="pre">SERIAL</span></code> column is populated with values from a <a class="reference external" href="https://www.postgresql.org/docs/current/sql-createsequence.html">sequence</a> that
keeps track of the next available value. Manually assigning a value to an
auto-incrementing field doesn’t update the field’s sequence, which might later
cause a conflict. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="k">import</span> <span class="n">User</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">&#39;alice&#39;</span><span class="p">,</span> <span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&lt;User: alice&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The sequence hasn&#39;t been updated; its next value is 1.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">&#39;bob&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">IntegrityError: duplicate key value violates unique constraint</span>
<span class="go">&quot;auth_user_pkey&quot; DETAIL:  Key (id)=(1) already exists.</span>
</pre></div>
</div>
<p>If you need to specify such values, reset the sequence afterwards to avoid
reusing a value that’s already in the table. The <a class="reference internal" href="django-admin.html#django-admin-sqlsequencereset"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">sqlsequencereset</span></code></a>
management command generates the SQL statements to do that.</p>
</div>
<div class="section" id="s-test-database-templates">
<span id="test-database-templates"></span><h3>Test database templates<a class="headerlink" href="#test-database-templates" title="Permalink to this headline">¶</a></h3>
<p>You can use the <a class="reference internal" href="settings.html#std:setting-TEST_TEMPLATE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TEST['TEMPLATE']</span></code></a> setting to specify
a <a class="reference external" href="https://www.postgresql.org/docs/current/sql-createdatabase.html">template</a> (e.g. <code class="docutils literal notranslate"><span class="pre">'template0'</span></code>) from which to create a test database.</p>
</div>
<div class="section" id="s-speeding-up-test-execution-with-non-durable-settings">
<span id="speeding-up-test-execution-with-non-durable-settings"></span><h3>Speeding up test execution with non-durable settings<a class="headerlink" href="#speeding-up-test-execution-with-non-durable-settings" title="Permalink to this headline">¶</a></h3>
<p>You can speed up test execution times by <a class="reference external" href="https://www.postgresql.org/docs/current/non-durability.html">configuring PostgreSQL to be
non-durable</a>.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">This is dangerous: it will make your database more susceptible to data loss
or corruption in the case of a server crash or power loss. Only use this on
a development machine where you can easily restore the entire contents of
all databases in the cluster.</p>
</div>
</div>
</div>
<div class="section" id="s-mysql-notes">
<span id="s-id3"></span><span id="mysql-notes"></span><span id="id3"></span><h2>MySQL notes<a class="headerlink" href="#mysql-notes" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-version-support">
<span id="version-support"></span><h3>Version support<a class="headerlink" href="#version-support" title="Permalink to this headline">¶</a></h3>
<p>Django supports MySQL 5.6 and higher.</p>
<p>Django’s <code class="docutils literal notranslate"><span class="pre">inspectdb</span></code> feature uses the <code class="docutils literal notranslate"><span class="pre">information_schema</span></code> database, which
contains detailed data on all database schemas.</p>
<p>Django expects the database to support Unicode (UTF-8 encoding) and delegates to
it the task of enforcing transactions and referential integrity. It is important
to be aware of the fact that the two latter ones aren’t actually enforced by
MySQL when using the MyISAM storage engine, see the next section.</p>
</div>
<div class="section" id="s-storage-engines">
<span id="s-mysql-storage-engines"></span><span id="storage-engines"></span><span id="mysql-storage-engines"></span><h3>Storage engines<a class="headerlink" href="#storage-engines" title="Permalink to this headline">¶</a></h3>
<p>MySQL has several <a class="reference external" href="https://dev.mysql.com/doc/refman/en/storage-engines.html">storage engines</a>. You can change the default storage engine
in the server configuration.</p>
<p>MySQL’s default storage engine is <a class="reference external" href="https://dev.mysql.com/doc/refman/en/innodb-storage-engine.html">InnoDB</a>. This engine is fully transactional
and supports foreign key references. It’s the recommended choice. However, the
InnoDB autoincrement counter is lost on a MySQL restart because it does not
remember the <code class="docutils literal notranslate"><span class="pre">AUTO_INCREMENT</span></code> value, instead recreating it as “max(id)+1”.
This may result in an inadvertent reuse of <a class="reference internal" href="models/fields.html#django.db.models.AutoField" title="django.db.models.AutoField"><code class="xref py py-class docutils literal notranslate"><span class="pre">AutoField</span></code></a>
values.</p>
<p>The main drawbacks of <a class="reference external" href="https://dev.mysql.com/doc/refman/en/myisam-storage-engine.html">MyISAM</a> are that it doesn’t support transactions or
enforce foreign-key constraints.</p>
</div>
<div class="section" id="s-mysql-db-api-drivers">
<span id="s-id5"></span><span id="mysql-db-api-drivers"></span><span id="id5"></span><h3>MySQL DB API Drivers<a class="headerlink" href="#mysql-db-api-drivers" title="Permalink to this headline">¶</a></h3>
<p>MySQL has a couple drivers that implement the Python Database API described in
<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>:</p>
<ul class="simple">
<li><a class="reference external" href="https://pypi.org/project/mysqlclient/">mysqlclient</a> is a native driver. It’s <strong>the recommended choice</strong>.</li>
<li><a class="reference external" href="https://dev.mysql.com/downloads/connector/python">MySQL Connector/Python</a> is a pure Python driver from Oracle that does not
require the MySQL client library or any Python modules outside the standard
library.</li>
</ul>
<p>These drivers are thread-safe and provide connection pooling.</p>
<p>In addition to a DB API driver, Django needs an adapter to access the database
drivers from its ORM. Django provides an adapter for mysqlclient while MySQL
Connector/Python includes <a class="reference external" href="https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html">its own</a>.</p>
<div class="section" id="s-id6">
<span id="id6"></span><h4>mysqlclient<a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h4>
<p>Django requires <a class="reference external" href="https://pypi.org/project/mysqlclient/">mysqlclient</a> 1.3.13 or later.</p>
</div>
<div class="section" id="s-id7">
<span id="id7"></span><h4>MySQL Connector/Python<a class="headerlink" href="#id7" title="Permalink to this headline">¶</a></h4>
<p>MySQL Connector/Python is available from the <a class="reference external" href="https://dev.mysql.com/downloads/connector/python/">download page</a>.
The Django adapter is available in versions 1.1.X and later. It may not
support the most recent releases of Django.</p>
</div>
</div>
<div class="section" id="s-time-zone-definitions">
<span id="s-mysql-time-zone-definitions"></span><span id="time-zone-definitions"></span><span id="mysql-time-zone-definitions"></span><h3>Time zone definitions<a class="headerlink" href="#time-zone-definitions" title="Permalink to this headline">¶</a></h3>
<p>If you plan on using Django’s <a class="reference internal" href="../topics/i18n/timezones.html"><span class="doc">timezone support</span></a>,
use <a class="reference external" href="https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html">mysql_tzinfo_to_sql</a> to load time zone tables into the MySQL database.
This needs to be done just once for your MySQL server, not per database.</p>
</div>
<div class="section" id="s-creating-your-database">
<span id="creating-your-database"></span><h3>Creating your database<a class="headerlink" href="#creating-your-database" title="Permalink to this headline">¶</a></h3>
<p>You can <a class="reference external" href="https://dev.mysql.com/doc/refman/en/create-database.html">create your database</a> using the command-line tools and this SQL:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CREATE</span> <span class="n">DATABASE</span> <span class="o">&lt;</span><span class="n">dbname</span><span class="o">&gt;</span> <span class="n">CHARACTER</span> <span class="n">SET</span> <span class="n">utf8</span><span class="p">;</span>
</pre></div>
</div>
<p>This ensures all tables and columns will use UTF-8 by default.</p>
<div class="section" id="s-collation-settings">
<span id="s-mysql-collation"></span><span id="collation-settings"></span><span id="mysql-collation"></span><h4>Collation settings<a class="headerlink" href="#collation-settings" title="Permalink to this headline">¶</a></h4>
<p>The collation setting for a column controls the order in which data is sorted
as well as what strings compare as equal. It can be set on a database-wide
level and also per-table and per-column. This is <a class="reference external" href="https://dev.mysql.com/doc/refman/en/charset.html">documented thoroughly</a> in
the MySQL documentation. In all cases, you set the collation by directly
manipulating the database tables; Django doesn’t provide a way to set this on
the model definition.</p>
<p>By default, with a UTF-8 database, MySQL will use the
<code class="docutils literal notranslate"><span class="pre">utf8_general_ci</span></code> collation. This results in all string equality
comparisons being done in a <em>case-insensitive</em> manner. That is, <code class="docutils literal notranslate"><span class="pre">&quot;Fred&quot;</span></code> and
<code class="docutils literal notranslate"><span class="pre">&quot;freD&quot;</span></code> are considered equal at the database level. If you have a unique
constraint on a field, it would be illegal to try to insert both <code class="docutils literal notranslate"><span class="pre">&quot;aa&quot;</span></code> and
<code class="docutils literal notranslate"><span class="pre">&quot;AA&quot;</span></code> into the same column, since they compare as equal (and, hence,
non-unique) with the default collation. If you want case-sensitive comparisons
on a particular column or table, change the column or table to use the
<code class="docutils literal notranslate"><span class="pre">utf8_bin</span></code> collation.</p>
<p>Please note that according to <a class="reference external" href="https://dev.mysql.com/doc/refman/en/charset-unicode-sets.html">MySQL Unicode Character Sets</a>, comparisons for
the <code class="docutils literal notranslate"><span class="pre">utf8_general_ci</span></code> collation are faster, but slightly less correct, than
comparisons for <code class="docutils literal notranslate"><span class="pre">utf8_unicode_ci</span></code>. If this is acceptable for your application,
you should use <code class="docutils literal notranslate"><span class="pre">utf8_general_ci</span></code> because it is faster. If this is not acceptable
(for example, if you require German dictionary order), use <code class="docutils literal notranslate"><span class="pre">utf8_unicode_ci</span></code>
because it is more accurate.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Model formsets validate unique fields in a case-sensitive manner. Thus when
using a case-insensitive collation, a formset with unique field values that
differ only by case will pass validation, but upon calling <code class="docutils literal notranslate"><span class="pre">save()</span></code>, an
<code class="docutils literal notranslate"><span class="pre">IntegrityError</span></code> will be raised.</p>
</div>
</div>
</div>
<div class="section" id="s-connecting-to-the-database">
<span id="connecting-to-the-database"></span><h3>Connecting to the database<a class="headerlink" href="#connecting-to-the-database" title="Permalink to this headline">¶</a></h3>
<p>Refer to the <a class="reference internal" href="settings.html"><span class="doc">settings documentation</span></a>.</p>
<p>Connection settings are used in this order:</p>
<ol class="arabic simple">
<li><a class="reference internal" href="settings.html#std:setting-OPTIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">OPTIONS</span></code></a>.</li>
<li><a class="reference internal" href="settings.html#std:setting-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a>, <a class="reference internal" href="settings.html#std:setting-USER"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USER</span></code></a>, <a class="reference internal" href="settings.html#std:setting-PASSWORD"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PASSWORD</span></code></a>, <a class="reference internal" href="settings.html#std:setting-HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">HOST</span></code></a>,
<a class="reference internal" href="settings.html#std:setting-PORT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PORT</span></code></a></li>
<li>MySQL option files.</li>
</ol>
<p>In other words, if you set the name of the database in <a class="reference internal" href="settings.html#std:setting-OPTIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">OPTIONS</span></code></a>,
this will take precedence over <a class="reference internal" href="settings.html#std:setting-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a>, which would override
anything in a <a class="reference external" href="https://dev.mysql.com/doc/refman/en/option-files.html">MySQL option file</a>.</p>
<p>Here’s a sample configuration which uses a MySQL option file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># settings.py</span>
<span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s1">&#39;django.db.backends.mysql&#39;</span><span class="p">,</span>
        <span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;read_default_file&#39;</span><span class="p">:</span> <span class="s1">&#39;/path/to/my.cnf&#39;</span><span class="p">,</span>
        <span class="p">},</span>
    <span class="p">}</span>
<span class="p">}</span>


<span class="c1"># my.cnf</span>
<span class="p">[</span><span class="n">client</span><span class="p">]</span>
<span class="n">database</span> <span class="o">=</span> <span class="n">NAME</span>
<span class="n">user</span> <span class="o">=</span> <span class="n">USER</span>
<span class="n">password</span> <span class="o">=</span> <span class="n">PASSWORD</span>
<span class="n">default</span><span class="o">-</span><span class="n">character</span><span class="o">-</span><span class="nb">set</span> <span class="o">=</span> <span class="n">utf8</span>
</pre></div>
</div>
<p>Several other <a class="reference external" href="https://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes">MySQLdb connection options</a> may be useful, such as <code class="docutils literal notranslate"><span class="pre">ssl</span></code>,
<code class="docutils literal notranslate"><span class="pre">init_command</span></code>, and <code class="docutils literal notranslate"><span class="pre">sql_mode</span></code>.</p>
<div class="section" id="s-setting-sql-mode">
<span id="s-mysql-sql-mode"></span><span id="setting-sql-mode"></span><span id="mysql-sql-mode"></span><h4>Setting <code class="docutils literal notranslate"><span class="pre">sql_mode</span></code><a class="headerlink" href="#setting-sql-mode" title="Permalink to this headline">¶</a></h4>
<p>From MySQL 5.7 onwards and on fresh installs of MySQL 5.6, the default value of
the <code class="docutils literal notranslate"><span class="pre">sql_mode</span></code> option contains <code class="docutils literal notranslate"><span class="pre">STRICT_TRANS_TABLES</span></code>. That option escalates
warnings into errors when data are truncated upon insertion, so Django highly
recommends activating a <a class="reference external" href="https://dev.mysql.com/doc/refman/en/sql-mode.html#sql-mode-strict">strict mode</a> for MySQL to prevent data loss (either
<code class="docutils literal notranslate"><span class="pre">STRICT_TRANS_TABLES</span></code> or <code class="docutils literal notranslate"><span class="pre">STRICT_ALL_TABLES</span></code>).</p>
<p>If you need to customize the SQL mode, you can set the <code class="docutils literal notranslate"><span class="pre">sql_mode</span></code> variable
like other MySQL options: either in a config file or with the entry
<code class="docutils literal notranslate"><span class="pre">'init_command':</span> <span class="pre">&quot;SET</span> <span class="pre">sql_mode='STRICT_TRANS_TABLES'&quot;</span></code> in the
<a class="reference internal" href="settings.html#std:setting-OPTIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">OPTIONS</span></code></a> part of your database configuration in <a class="reference internal" href="settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a>.</p>
</div>
<div class="section" id="s-mysql-isolation-level">
<span id="s-id8"></span><span id="mysql-isolation-level"></span><span id="id8"></span><h4>Isolation level<a class="headerlink" href="#mysql-isolation-level" title="Permalink to this headline">¶</a></h4>
<p>When running concurrent loads, database transactions from different sessions
(say, separate threads handling different requests) may interact with each
other. These interactions are affected by each session’s <a class="reference external" href="https://dev.mysql.com/doc/refman/en/innodb-transaction-isolation-levels.html">transaction isolation
level</a>. You can set a connection’s isolation level with an
<code class="docutils literal notranslate"><span class="pre">'isolation_level'</span></code> entry in the <a class="reference internal" href="settings.html#std:setting-OPTIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">OPTIONS</span></code></a> part of your database
configuration in <a class="reference internal" href="settings.html#std:setting-DATABASES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">DATABASES</span></code></a>. Valid values for
this entry are the four standard isolation levels:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">'read</span> <span class="pre">uncommitted'</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">'read</span> <span class="pre">committed'</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">'repeatable</span> <span class="pre">read'</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">'serializable'</span></code></li>
</ul>
<p>or <code class="docutils literal notranslate"><span class="pre">None</span></code> to use the server’s configured isolation level. However, Django
works best with and defaults to read committed rather than MySQL’s default,
repeatable read. Data loss is possible with repeatable read. In particular,
you may see cases where <a class="reference internal" href="models/querysets.html#django.db.models.query.QuerySet.get_or_create" title="django.db.models.query.QuerySet.get_or_create"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_or_create()</span></code></a>
will raise an <a class="reference internal" href="exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IntegrityError</span></code></a> but the object won’t appear in
a subsequent <a class="reference internal" href="models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> call.</p>
</div>
</div>
<div class="section" id="s-creating-your-tables">
<span id="creating-your-tables"></span><h3>Creating your tables<a class="headerlink" href="#creating-your-tables" title="Permalink to this headline">¶</a></h3>
<p>When Django generates the schema, it doesn’t specify a storage engine, so
tables will be created with whatever default storage engine your database
server is configured for. The easiest solution is to set your database server’s
default storage engine to the desired engine.</p>
<p>If you’re using a hosting service and can’t change your server’s default
storage engine, you have a couple of options.</p>
<ul>
<li><p class="first">After the tables are created, execute an <code class="docutils literal notranslate"><span class="pre">ALTER</span> <span class="pre">TABLE</span></code> statement to
convert a table to a new storage engine (such as InnoDB):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ALTER</span> <span class="n">TABLE</span> <span class="o">&lt;</span><span class="n">tablename</span><span class="o">&gt;</span> <span class="n">ENGINE</span><span class="o">=</span><span class="n">INNODB</span><span class="p">;</span>
</pre></div>
</div>
<p>This can be tedious if you have a lot of tables.</p>
</li>
<li><p class="first">Another option is to use the <code class="docutils literal notranslate"><span class="pre">init_command</span></code> option for MySQLdb prior to
creating your tables:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
   <span class="s1">&#39;init_command&#39;</span><span class="p">:</span> <span class="s1">&#39;SET default_storage_engine=INNODB&#39;</span><span class="p">,</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This sets the default storage engine upon connecting to the database.
After your tables have been created, you should remove this option as it
adds a query that is only needed during table creation to each database
connection.</p>
</li>
</ul>
</div>
<div class="section" id="s-table-names">
<span id="table-names"></span><h3>Table names<a class="headerlink" href="#table-names" title="Permalink to this headline">¶</a></h3>
<p>There are <a class="reference external" href="https://bugs.mysql.com/bug.php?id=48875">known issues</a> in even the latest versions of MySQL that can cause the
case of a table name to be altered when certain SQL statements are executed
under certain conditions. It is recommended that you use lowercase table
names, if possible, to avoid any problems that might arise from this behavior.
Django uses lowercase table names when it auto-generates table names from
models, so this is mainly a consideration if you are overriding the table name
via the <a class="reference internal" href="models/options.html#django.db.models.Options.db_table" title="django.db.models.Options.db_table"><code class="xref py py-class docutils literal notranslate"><span class="pre">db_table</span></code></a> parameter.</p>
</div>
<div class="section" id="s-savepoints">
<span id="savepoints"></span><h3>Savepoints<a class="headerlink" href="#savepoints" title="Permalink to this headline">¶</a></h3>
<p>Both the Django ORM and MySQL (when using the InnoDB <a class="reference internal" href="#mysql-storage-engines"><span class="std std-ref">storage engine</span></a>) support database <a class="reference internal" href="../topics/db/transactions.html#topics-db-transactions-savepoints"><span class="std std-ref">savepoints</span></a>.</p>
<p>If you use the MyISAM storage engine please be aware of the fact that you will
receive database-generated errors if you try to use the <a class="reference internal" href="../topics/db/transactions.html#topics-db-transactions-savepoints"><span class="std std-ref">savepoint-related
methods of the transactions API</span></a>. The reason
for this is that detecting the storage engine of a MySQL database/table is an
expensive operation so it was decided it isn’t worth to dynamically convert
these methods in no-op’s based in the results of such detection.</p>
</div>
<div class="section" id="s-notes-on-specific-fields">
<span id="notes-on-specific-fields"></span><h3>Notes on specific fields<a class="headerlink" href="#notes-on-specific-fields" title="Permalink to this headline">¶</a></h3>
<div class="section" id="s-character-fields">
<span id="character-fields"></span><h4>Character fields<a class="headerlink" href="#character-fields" title="Permalink to this headline">¶</a></h4>
<p>Any fields that are stored with <code class="docutils literal notranslate"><span class="pre">VARCHAR</span></code> column types have their
<code class="docutils literal notranslate"><span class="pre">max_length</span></code> restricted to 255 characters if you are using <code class="docutils literal notranslate"><span class="pre">unique=True</span></code>
for the field. This affects <a class="reference internal" href="models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a>,
<a class="reference internal" href="models/fields.html#django.db.models.SlugField" title="django.db.models.SlugField"><code class="xref py py-class docutils literal notranslate"><span class="pre">SlugField</span></code></a>.</p>
</div>
<div class="section" id="s-textfield-limitations">
<span id="textfield-limitations"></span><h4><code class="docutils literal notranslate"><span class="pre">TextField</span></code> limitations<a class="headerlink" href="#textfield-limitations" title="Permalink to this headline">¶</a></h4>
<p>MySQL can index only the first N chars of a <code class="docutils literal notranslate"><span class="pre">BLOB</span></code> or <code class="docutils literal notranslate"><span class="pre">TEXT</span></code> column. Since
<code class="docutils literal notranslate"><span class="pre">TextField</span></code> doesn’t have a defined length, you can’t mark it as
<code class="docutils literal notranslate"><span class="pre">unique=True</span></code>. MySQL will report: “BLOB/TEXT column ‘&lt;db_column&gt;’ used in key
specification without a key length”.</p>
</div>
<div class="section" id="s-fractional-seconds-support-for-time-and-datetime-fields">
<span id="s-mysql-fractional-seconds"></span><span id="fractional-seconds-support-for-time-and-datetime-fields"></span><span id="mysql-fractional-seconds"></span><h4>Fractional seconds support for Time and DateTime fields<a class="headerlink" href="#fractional-seconds-support-for-time-and-datetime-fields" title="Permalink to this headline">¶</a></h4>
<p>MySQL 5.6.4 and later can store fractional seconds, provided that the
column definition includes a fractional indication (e.g. <code class="docutils literal notranslate"><span class="pre">DATETIME(6)</span></code>).
Earlier versions do not support them at all.</p>
<p>Django will not upgrade existing columns to include fractional seconds if the
database server supports it. If you want to enable them on an existing database,
it’s up to you to either manually update the column on the target database, by
executing a command like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>ALTER TABLE `your_table` MODIFY `your_datetime_column` DATETIME(6)
</pre></div>
</div>
<p>or using a <a class="reference internal" href="migration-operations.html#django.db.migrations.operations.RunSQL" title="django.db.migrations.operations.RunSQL"><code class="xref py py-class docutils literal notranslate"><span class="pre">RunSQL</span></code></a> operation in a
<a class="reference internal" href="../topics/migrations.html#data-migrations"><span class="std std-ref">data migration</span></a>.</p>
</div>
<div class="section" id="s-timestamp-columns">
<span id="timestamp-columns"></span><h4><code class="docutils literal notranslate"><span class="pre">TIMESTAMP</span></code> columns<a class="headerlink" href="#timestamp-columns" title="Permalink to this headline">¶</a></h4>
<p>If you are using a legacy database that contains <code class="docutils literal notranslate"><span class="pre">TIMESTAMP</span></code> columns, you must
set <a class="reference internal" href="settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span> <span class="pre">=</span> <span class="pre">False</span></code></a> to avoid data corruption.
<a class="reference internal" href="django-admin.html#django-admin-inspectdb"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">inspectdb</span></code></a> maps these columns to
<a class="reference internal" href="models/fields.html#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTimeField</span></code></a> and if you enable timezone support,
both MySQL and Django will attempt to convert the values from UTC to local time.</p>
</div>
</div>
<div class="section" id="s-row-locking-with-queryset-select-for-update">
<span id="row-locking-with-queryset-select-for-update"></span><h3>Row locking with <code class="docutils literal notranslate"><span class="pre">QuerySet.select_for_update()</span></code><a class="headerlink" href="#row-locking-with-queryset-select-for-update" title="Permalink to this headline">¶</a></h3>
<p>MySQL does not support some options to the <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></code> statement.
If <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> is used with an unsupported option, then
a <a class="reference internal" href="exceptions.html#django.db.NotSupportedError" title="django.db.NotSupportedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotSupportedError</span></code></a> is raised.</p>
<table class="docutils">
<colgroup>
<col width="60%" />
<col width="40%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Option</th>
<th class="head">MySQL</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">SKIP</span> <span class="pre">LOCKED</span></code></td>
<td>X (≥8.0.1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">NOWAIT</span></code></td>
<td>X (≥8.0.1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">OF</span></code></td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>When using <code class="docutils literal notranslate"><span class="pre">select_for_update()</span></code> on MySQL, make sure you filter a queryset
against at least set of fields contained in unique constraints or only against
fields covered by indexes. Otherwise, an exclusive write lock will be acquired
over the full table for the duration of the transaction.</p>
</div>
<div class="section" id="s-automatic-typecasting-can-cause-unexpected-results">
<span id="automatic-typecasting-can-cause-unexpected-results"></span><h3>Automatic typecasting can cause unexpected results<a class="headerlink" href="#automatic-typecasting-can-cause-unexpected-results" title="Permalink to this headline">¶</a></h3>
<p>When performing a query on a string type, but with an integer value, MySQL will
coerce the types of all values in the table to an integer before performing the
comparison. If your table contains the values <code class="docutils literal notranslate"><span class="pre">'abc'</span></code>, <code class="docutils literal notranslate"><span class="pre">'def'</span></code> and you
query for <code class="docutils literal notranslate"><span class="pre">WHERE</span> <span class="pre">mycolumn=0</span></code>, both rows will match. Similarly, <code class="docutils literal notranslate"><span class="pre">WHERE</span> <span class="pre">mycolumn=1</span></code>
will match the value <code class="docutils literal notranslate"><span class="pre">'abc1'</span></code>. Therefore, string type fields included in Django
will always cast the value to a string before using it in a query.</p>
<p>If you implement custom model fields that inherit from
<a class="reference internal" href="models/fields.html#django.db.models.Field" title="django.db.models.Field"><code class="xref py py-class docutils literal notranslate"><span class="pre">Field</span></code></a> directly, are overriding
<a class="reference internal" href="models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_prep_value()</span></code></a>, or use
<a class="reference internal" href="models/expressions.html#django.db.models.expressions.RawSQL" title="django.db.models.expressions.RawSQL"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawSQL</span></code></a>,
<a class="reference internal" href="models/querysets.html#django.db.models.query.QuerySet.extra" title="django.db.models.query.QuerySet.extra"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extra()</span></code></a>, or
<a class="reference internal" href="../topics/db/sql.html#django.db.models.Manager.raw" title="django.db.models.Manager.raw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">raw()</span></code></a>, you should ensure that you perform
appropriate typecasting.</p>
</div>
</div>
<div class="section" id="s-sqlite-notes">
<span id="s-id9"></span><span id="sqlite-notes"></span><span id="id9"></span><h2>SQLite notes<a class="headerlink" href="#sqlite-notes" title="Permalink to this headline">¶</a></h2>
<p>Django supports SQLite 3.8.3 and later.</p>
<p><a class="reference external" href="https://www.sqlite.org/">SQLite</a> provides an excellent development alternative for applications that
are predominantly read-only or require a smaller installation footprint. As
with all database servers, though, there are some differences that are
specific to SQLite that you should be aware of.</p>
<div class="section" id="s-substring-matching-and-case-sensitivity">
<span id="s-sqlite-string-matching"></span><span id="substring-matching-and-case-sensitivity"></span><span id="sqlite-string-matching"></span><h3>Substring matching and case sensitivity<a class="headerlink" href="#substring-matching-and-case-sensitivity" title="Permalink to this headline">¶</a></h3>
<p>For all SQLite versions, there is some slightly counter-intuitive behavior when
attempting to match some types of strings.  These are triggered when using the
<a class="reference internal" href="models/querysets.html#std:fieldlookup-iexact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iexact</span></code></a> or <a class="reference internal" href="models/querysets.html#std:fieldlookup-contains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">contains</span></code></a> filters in Querysets. The behavior
splits into two cases:</p>
<p>1. For substring matching, all matches are done case-insensitively. That is a
filter such as <code class="docutils literal notranslate"><span class="pre">filter(name__contains=&quot;aa&quot;)</span></code> will match a name of <code class="docutils literal notranslate"><span class="pre">&quot;Aabb&quot;</span></code>.</p>
<p>2. For strings containing characters outside the ASCII range, all exact string
matches are performed case-sensitively, even when the case-insensitive options
are passed into the query. So the <a class="reference internal" href="models/querysets.html#std:fieldlookup-iexact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iexact</span></code></a> filter will behave exactly
the same as the <a class="reference internal" href="models/querysets.html#std:fieldlookup-exact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">exact</span></code></a> filter in these cases.</p>
<p>Some possible workarounds for this are <a class="reference external" href="https://www.sqlite.org/faq.html#q18">documented at sqlite.org</a>, but they
aren’t utilized by the default SQLite backend in Django, as incorporating them
would be fairly difficult to do robustly. Thus, Django exposes the default
SQLite behavior and you should be aware of this when doing case-insensitive or
substring filtering.</p>
</div>
<div class="section" id="s-decimal-handling">
<span id="s-sqlite-decimal-handling"></span><span id="decimal-handling"></span><span id="sqlite-decimal-handling"></span><h3>Decimal handling<a class="headerlink" href="#decimal-handling" title="Permalink to this headline">¶</a></h3>
<p>SQLite has no real decimal internal type. Decimal values are internally
converted to the <code class="docutils literal notranslate"><span class="pre">REAL</span></code> data type (8-byte IEEE floating point number), as
explained in the <a class="reference external" href="https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes">SQLite datatypes documentation</a>, so they don’t support
correctly-rounded decimal floating point arithmetic.</p>
</div>
<div class="section" id="s-database-is-locked-errors">
<span id="database-is-locked-errors"></span><h3>“Database is locked” errors<a class="headerlink" href="#database-is-locked-errors" title="Permalink to this headline">¶</a></h3>
<p>SQLite is meant to be a lightweight database, and thus can’t support a high
level of concurrency. <code class="docutils literal notranslate"><span class="pre">OperationalError:</span> <span class="pre">database</span> <span class="pre">is</span> <span class="pre">locked</span></code> errors indicate
that your application is experiencing more concurrency than <code class="docutils literal notranslate"><span class="pre">sqlite</span></code> can
handle in default configuration. This error means that one thread or process has
an exclusive lock on the database connection and another thread timed out
waiting for the lock the be released.</p>
<p>Python’s SQLite wrapper has
a default timeout value that determines how long the second thread is allowed to
wait on the lock before it times out and raises the <code class="docutils literal notranslate"><span class="pre">OperationalError:</span> <span class="pre">database</span>
<span class="pre">is</span> <span class="pre">locked</span></code> error.</p>
<p>If you’re getting this error, you can solve it by:</p>
<ul>
<li><p class="first">Switching to another database backend. At a certain point SQLite becomes
too “lite” for real-world applications, and these sorts of concurrency
errors indicate you’ve reached that point.</p>
</li>
<li><p class="first">Rewriting your code to reduce concurrency and ensure that database
transactions are short-lived.</p>
</li>
<li><p class="first">Increase the default timeout value by setting the <code class="docutils literal notranslate"><span class="pre">timeout</span></code> database
option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
    <span class="c1"># ...</span>
    <span class="s1">&#39;timeout&#39;</span><span class="p">:</span> <span class="mi">20</span><span class="p">,</span>
    <span class="c1"># ...</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This will simply make SQLite wait a bit longer before throwing “database
is locked” errors; it won’t really do anything to solve them.</p>
</li>
</ul>
</div>
<div class="section" id="s-queryset-select-for-update-not-supported">
<span id="queryset-select-for-update-not-supported"></span><h3><code class="docutils literal notranslate"><span class="pre">QuerySet.select_for_update()</span></code> not supported<a class="headerlink" href="#queryset-select-for-update-not-supported" title="Permalink to this headline">¶</a></h3>
<p>SQLite does not support the <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">...</span> <span class="pre">FOR</span> <span class="pre">UPDATE</span></code> syntax. Calling it will
have no effect.</p>
</div>
<div class="section" id="s-pyformat-parameter-style-in-raw-queries-not-supported">
<span id="pyformat-parameter-style-in-raw-queries-not-supported"></span><h3>“pyformat” parameter style in raw queries not supported<a class="headerlink" href="#pyformat-parameter-style-in-raw-queries-not-supported" title="Permalink to this headline">¶</a></h3>
<p>For most backends, raw queries (<code class="docutils literal notranslate"><span class="pre">Manager.raw()</span></code> or <code class="docutils literal notranslate"><span class="pre">cursor.execute()</span></code>)
can use the “pyformat” parameter style, where placeholders in the query
are given as <code class="docutils literal notranslate"><span class="pre">'%(name)s'</span></code> and the parameters are passed as a dictionary
rather than a list. SQLite does not support this.</p>
</div>
<div class="section" id="s-isolation-when-using-queryset-iterator">
<span id="s-sqlite-isolation"></span><span id="isolation-when-using-queryset-iterator"></span><span id="sqlite-isolation"></span><h3>Isolation when using <code class="docutils literal notranslate"><span class="pre">QuerySet.iterator()</span></code><a class="headerlink" href="#isolation-when-using-queryset-iterator" title="Permalink to this headline">¶</a></h3>
<p>There are special considerations described in <a class="reference external" href="https://sqlite.org/isolation.html">Isolation In SQLite</a> when
modifying a table while iterating over it using <a class="reference internal" href="models/querysets.html#django.db.models.query.QuerySet.iterator" title="django.db.models.query.QuerySet.iterator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">QuerySet.iterator()</span></code></a>. If
a row is added, changed, or deleted within the loop, then that row may or may
not appear, or may appear twice, in subsequent results fetched from the
iterator. Your code must handle this.</p>
</div>
</div>
<div class="section" id="s-oracle-notes">
<span id="s-id11"></span><span id="oracle-notes"></span><span id="id11"></span><h2>Oracle notes<a class="headerlink" href="#oracle-notes" title="Permalink to this headline">¶</a></h2>
<p>Django supports <a class="reference external" href="https://www.oracle.com/">Oracle Database Server</a> versions 12.1 and higher. Version
6.0 or higher of the <a class="reference external" href="https://oracle.github.io/python-cx_Oracle/">cx_Oracle</a> Python driver is required.</p>
<p>In order for the <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">migrate</span></code> command to work, your Oracle
database user must have privileges to run the following commands:</p>
<ul class="simple">
<li>CREATE TABLE</li>
<li>CREATE SEQUENCE</li>
<li>CREATE PROCEDURE</li>
<li>CREATE TRIGGER</li>
</ul>
<p>To run a project’s test suite, the user usually needs these <em>additional</em>
privileges:</p>
<ul class="simple">
<li>CREATE USER</li>
<li>ALTER USER</li>
<li>DROP USER</li>
<li>CREATE TABLESPACE</li>
<li>DROP TABLESPACE</li>
<li>CREATE SESSION WITH ADMIN OPTION</li>
<li>CREATE TABLE WITH ADMIN OPTION</li>
<li>CREATE SEQUENCE WITH ADMIN OPTION</li>
<li>CREATE PROCEDURE WITH ADMIN OPTION</li>
<li>CREATE TRIGGER WITH ADMIN OPTION</li>
</ul>
<p>While the <code class="docutils literal notranslate"><span class="pre">RESOURCE</span></code> role has the required <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code>,
<code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">SEQUENCE</span></code>, <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">PROCEDURE</span></code>, and <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">TRIGGER</span></code> privileges,
and a user granted <code class="docutils literal notranslate"><span class="pre">RESOURCE</span> <span class="pre">WITH</span> <span class="pre">ADMIN</span> <span class="pre">OPTION</span></code> can grant <code class="docutils literal notranslate"><span class="pre">RESOURCE</span></code>, such
a user cannot grant the individual privileges (e.g. <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code>), and thus
<code class="docutils literal notranslate"><span class="pre">RESOURCE</span> <span class="pre">WITH</span> <span class="pre">ADMIN</span> <span class="pre">OPTION</span></code> is not usually sufficient for running tests.</p>
<p>Some test suites also create views or materialized views; to run these, the
user also needs <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">VIEW</span> <span class="pre">WITH</span> <span class="pre">ADMIN</span> <span class="pre">OPTION</span></code> and
<code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">MATERIALIZED</span> <span class="pre">VIEW</span> <span class="pre">WITH</span> <span class="pre">ADMIN</span> <span class="pre">OPTION</span></code> privileges. In particular, this
is needed for Django’s own test suite.</p>
<p>All of these privileges are included in the DBA role, which is appropriate
for use on a private developer’s database.</p>
<p>The Oracle database backend uses the <code class="docutils literal notranslate"><span class="pre">SYS.DBMS_LOB</span></code> and <code class="docutils literal notranslate"><span class="pre">SYS.DBMS_RANDOM</span></code>
packages, so your user will require execute permissions on it. It’s normally
accessible to all users by default, but in case it is not, you’ll need to grant
permissions like so:</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">GRANT</span> <span class="k">EXECUTE</span> <span class="k">ON</span> <span class="n">SYS</span><span class="p">.</span><span class="n">DBMS_LOB</span> <span class="k">TO</span> <span class="k">user</span><span class="p">;</span>
<span class="k">GRANT</span> <span class="k">EXECUTE</span> <span class="k">ON</span> <span class="n">SYS</span><span class="p">.</span><span class="n">DBMS_RANDOM</span> <span class="k">TO</span> <span class="k">user</span><span class="p">;</span>
</pre></div>
</div>
<div class="section" id="s-id12">
<span id="id12"></span><h3>Connecting to the database<a class="headerlink" href="#id12" title="Permalink to this headline">¶</a></h3>
<p>To connect using the service name of your Oracle database, your <code class="docutils literal notranslate"><span class="pre">settings.py</span></code>
file should look something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s1">&#39;django.db.backends.oracle&#39;</span><span class="p">,</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;xe&#39;</span><span class="p">,</span>
        <span class="s1">&#39;USER&#39;</span><span class="p">:</span> <span class="s1">&#39;a_user&#39;</span><span class="p">,</span>
        <span class="s1">&#39;PASSWORD&#39;</span><span class="p">:</span> <span class="s1">&#39;a_password&#39;</span><span class="p">,</span>
        <span class="s1">&#39;HOST&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
        <span class="s1">&#39;PORT&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In this case, you should leave both <a class="reference internal" href="settings.html#std:setting-HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">HOST</span></code></a> and <a class="reference internal" href="settings.html#std:setting-PORT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PORT</span></code></a> empty.
However, if you don’t use a <code class="docutils literal notranslate"><span class="pre">tnsnames.ora</span></code> file or a similar naming method
and want to connect using the SID (“xe” in this example), then fill in both
<a class="reference internal" href="settings.html#std:setting-HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">HOST</span></code></a> and <a class="reference internal" href="settings.html#std:setting-PORT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PORT</span></code></a> like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;ENGINE&#39;</span><span class="p">:</span> <span class="s1">&#39;django.db.backends.oracle&#39;</span><span class="p">,</span>
        <span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;xe&#39;</span><span class="p">,</span>
        <span class="s1">&#39;USER&#39;</span><span class="p">:</span> <span class="s1">&#39;a_user&#39;</span><span class="p">,</span>
        <span class="s1">&#39;PASSWORD&#39;</span><span class="p">:</span> <span class="s1">&#39;a_password&#39;</span><span class="p">,</span>
        <span class="s1">&#39;HOST&#39;</span><span class="p">:</span> <span class="s1">&#39;dbprod01ned.mycompany.com&#39;</span><span class="p">,</span>
        <span class="s1">&#39;PORT&#39;</span><span class="p">:</span> <span class="s1">&#39;1540&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>You should either supply both <a class="reference internal" href="settings.html#std:setting-HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">HOST</span></code></a> and <a class="reference internal" href="settings.html#std:setting-PORT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PORT</span></code></a>, or leave
both as empty strings. Django will use a different connect descriptor depending
on that choice.</p>
<div class="section" id="s-full-dsn-and-easy-connect">
<span id="full-dsn-and-easy-connect"></span><h4>Full DSN and Easy Connect<a class="headerlink" href="#full-dsn-and-easy-connect" title="Permalink to this headline">¶</a></h4>
<p>A Full DSN or Easy Connect string can be used in <a class="reference internal" href="settings.html#std:setting-NAME"><code class="xref std std-setting docutils literal notranslate"><span class="pre">NAME</span></code></a> if both
<a class="reference internal" href="settings.html#std:setting-HOST"><code class="xref std std-setting docutils literal notranslate"><span class="pre">HOST</span></code></a> and <a class="reference internal" href="settings.html#std:setting-PORT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">PORT</span></code></a> are empty. This format is required when
using RAC or pluggable databases without <code class="docutils literal notranslate"><span class="pre">tnsnames.ora</span></code>, for example.</p>
<p>Example of an Easy Connect string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="s1">&#39;localhost:1521/orclpdb1&#39;</span><span class="p">,</span>
</pre></div>
</div>
<p>Example of a full DSN string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;NAME&#39;</span><span class="p">:</span> <span class="p">(</span>
    <span class="s1">&#39;(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))&#39;</span>
    <span class="s1">&#39;(CONNECT_DATA=(SERVICE_NAME=orclpdb1)))&#39;</span>
<span class="p">),</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-threaded-option">
<span id="threaded-option"></span><h3>Threaded option<a class="headerlink" href="#threaded-option" title="Permalink to this headline">¶</a></h3>
<p>If you plan to run Django in a multithreaded environment (e.g. Apache using the
default MPM module on any modern operating system), then you <strong>must</strong> set
the <code class="docutils literal notranslate"><span class="pre">threaded</span></code> option of your Oracle database configuration to <code class="docutils literal notranslate"><span class="pre">True</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
    <span class="s1">&#39;threaded&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
<span class="p">},</span>
</pre></div>
</div>
<p>Failure to do this may result in crashes and other odd behavior.</p>
</div>
<div class="section" id="s-insert-returning-into">
<span id="insert-returning-into"></span><h3>INSERT … RETURNING INTO<a class="headerlink" href="#insert-returning-into" title="Permalink to this headline">¶</a></h3>
<p>By default, the Oracle backend uses a <code class="docutils literal notranslate"><span class="pre">RETURNING</span> <span class="pre">INTO</span></code> clause to efficiently
retrieve the value of an <code class="docutils literal notranslate"><span class="pre">AutoField</span></code> when inserting new rows.  This behavior
may result in a <code class="docutils literal notranslate"><span class="pre">DatabaseError</span></code> in certain unusual setups, such as when
inserting into a remote table, or into a view with an <code class="docutils literal notranslate"><span class="pre">INSTEAD</span> <span class="pre">OF</span></code> trigger.
The <code class="docutils literal notranslate"><span class="pre">RETURNING</span> <span class="pre">INTO</span></code> clause can be disabled by setting the
<code class="docutils literal notranslate"><span class="pre">use_returning_into</span></code> option of the database configuration to <code class="docutils literal notranslate"><span class="pre">False</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
    <span class="s1">&#39;use_returning_into&#39;</span><span class="p">:</span> <span class="kc">False</span><span class="p">,</span>
<span class="p">},</span>
</pre></div>
</div>
<p>In this case, the Oracle backend will use a separate <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> query to
retrieve <code class="docutils literal notranslate"><span class="pre">AutoField</span></code> values.</p>
</div>
<div class="section" id="s-naming-issues">
<span id="naming-issues"></span><h3>Naming issues<a class="headerlink" href="#naming-issues" title="Permalink to this headline">¶</a></h3>
<p>Oracle imposes a name length limit of 30 characters. To accommodate this, the
backend truncates database identifiers to fit, replacing the final four
characters of the truncated name with a repeatable MD5 hash value.
Additionally, the backend turns database identifiers to all-uppercase.</p>
<p>To prevent these transformations (this is usually required only when dealing
with legacy databases or accessing tables which belong to other users), use
a quoted name as the value for <code class="docutils literal notranslate"><span class="pre">db_table</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LegacyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">db_table</span> <span class="o">=</span> <span class="s1">&#39;&quot;name_left_in_lowercase&quot;&#39;</span>

<span class="k">class</span> <span class="nc">ForeignModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">db_table</span> <span class="o">=</span> <span class="s1">&#39;&quot;OTHER_USER&quot;.&quot;NAME_ONLY_SEEMS_OVER_30&quot;&#39;</span>
</pre></div>
</div>
<p>Quoted names can also be used with Django’s other supported database
backends; except for Oracle, however, the quotes have no effect.</p>
<p>When running <code class="docutils literal notranslate"><span class="pre">migrate</span></code>, an <code class="docutils literal notranslate"><span class="pre">ORA-06552</span></code> error may be encountered if
certain Oracle keywords are used as the name of a model field or the
value of a <code class="docutils literal notranslate"><span class="pre">db_column</span></code> option.  Django quotes all identifiers used
in queries to prevent most such problems, but this error can still
occur when an Oracle datatype is used as a column name.  In
particular, take care to avoid using the names <code class="docutils literal notranslate"><span class="pre">date</span></code>,
<code class="docutils literal notranslate"><span class="pre">timestamp</span></code>, <code class="docutils literal notranslate"><span class="pre">number</span></code> or <code class="docutils literal notranslate"><span class="pre">float</span></code> as a field name.</p>
</div>
<div class="section" id="s-null-and-empty-strings">
<span id="s-oracle-null-empty-strings"></span><span id="null-and-empty-strings"></span><span id="oracle-null-empty-strings"></span><h3>NULL and empty strings<a class="headerlink" href="#null-and-empty-strings" title="Permalink to this headline">¶</a></h3>
<p>Django generally prefers to use the empty string (<code class="docutils literal notranslate"><span class="pre">''</span></code>) rather than
<code class="docutils literal notranslate"><span class="pre">NULL</span></code>, but Oracle treats both identically. To get around this, the
Oracle backend ignores an explicit <code class="docutils literal notranslate"><span class="pre">null</span></code> option on fields that
have the empty string as a possible value and generates DDL as if
<code class="docutils literal notranslate"><span class="pre">null=True</span></code>. When fetching from the database, it is assumed that
a <code class="docutils literal notranslate"><span class="pre">NULL</span></code> value in one of these fields really means the empty
string, and the data is silently converted to reflect this assumption.</p>
</div>
<div class="section" id="s-id13">
<span id="id13"></span><h3><code class="docutils literal notranslate"><span class="pre">TextField</span></code> limitations<a class="headerlink" href="#id13" title="Permalink to this headline">¶</a></h3>
<p>The Oracle backend stores <code class="docutils literal notranslate"><span class="pre">TextFields</span></code> as <code class="docutils literal notranslate"><span class="pre">NCLOB</span></code> columns. Oracle imposes
some limitations on the usage of such LOB columns in general:</p>
<ul class="simple">
<li>LOB columns may not be used as primary keys.</li>
<li>LOB columns may not be used in indexes.</li>
<li>LOB columns may not be used in a <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span></code> list. This means that
attempting to use the <code class="docutils literal notranslate"><span class="pre">QuerySet.distinct</span></code> method on a model that
includes <code class="docutils literal notranslate"><span class="pre">TextField</span></code> columns will result in an <code class="docutils literal notranslate"><span class="pre">ORA-00932</span></code> error when
run against Oracle. As a workaround, use the <code class="docutils literal notranslate"><span class="pre">QuerySet.defer</span></code> method in
conjunction with <code class="docutils literal notranslate"><span class="pre">distinct()</span></code> to prevent <code class="docutils literal notranslate"><span class="pre">TextField</span></code> columns from being
included in the <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">DISTINCT</span></code> list.</li>
</ul>
</div>
</div>
<div class="section" id="s-using-a-3rd-party-database-backend">
<span id="s-third-party-notes"></span><span id="using-a-3rd-party-database-backend"></span><span id="third-party-notes"></span><h2>Using a 3rd-party database backend<a class="headerlink" href="#using-a-3rd-party-database-backend" title="Permalink to this headline">¶</a></h2>
<p>In addition to the officially supported databases, there are backends provided
by 3rd parties that allow you to use other databases with Django:</p>
<ul class="simple">
<li><a class="reference external" href="https://pypi.org/project/ibm_db_django/">IBM DB2</a></li>
<li><a class="reference external" href="https://pypi.org/project/django-pyodbc-azure/">Microsoft SQL Server</a></li>
<li><a class="reference external" href="https://github.com/maxirobaina/django-firebird">Firebird</a></li>
<li><a class="reference external" href="https://github.com/lionheart/django-pyodbc/">ODBC</a></li>
</ul>
<p>The Django versions and ORM features supported by these unofficial backends
vary considerably. Queries regarding the specific capabilities of these
unofficial backends, along with any support queries, should be directed to
the support channels provided by each 3rd party project.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Databases</a><ul>
<li><a class="reference internal" href="#general-notes">General notes</a><ul>
<li><a class="reference internal" href="#persistent-connections">Persistent connections</a><ul>
<li><a class="reference internal" href="#connection-management">Connection management</a></li>
<li><a class="reference internal" href="#caveats">Caveats</a></li>
</ul>
</li>
<li><a class="reference internal" href="#encoding">Encoding</a></li>
</ul>
</li>
<li><a class="reference internal" href="#postgresql-notes">PostgreSQL notes</a><ul>
<li><a class="reference internal" href="#postgresql-connection-settings">PostgreSQL connection settings</a></li>
<li><a class="reference internal" href="#optimizing-postgresql-s-configuration">Optimizing PostgreSQL’s configuration</a></li>
<li><a class="reference internal" href="#isolation-level">Isolation level</a></li>
<li><a class="reference internal" href="#indexes-for-varchar-and-text-columns">Indexes for <code class="docutils literal notranslate"><span class="pre">varchar</span></code> and <code class="docutils literal notranslate"><span class="pre">text</span></code> columns</a></li>
<li><a class="reference internal" href="#migration-operation-for-adding-extensions">Migration operation for adding extensions</a></li>
<li><a class="reference internal" href="#server-side-cursors">Server-side cursors</a><ul>
<li><a class="reference internal" href="#transaction-pooling-and-server-side-cursors">Transaction pooling and server-side cursors</a></li>
</ul>
</li>
<li><a class="reference internal" href="#manually-specifying-values-of-auto-incrementing-primary-keys">Manually-specifying values of auto-incrementing primary keys</a></li>
<li><a class="reference internal" href="#test-database-templates">Test database templates</a></li>
<li><a class="reference internal" href="#speeding-up-test-execution-with-non-durable-settings">Speeding up test execution with non-durable settings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#mysql-notes">MySQL notes</a><ul>
<li><a class="reference internal" href="#version-support">Version support</a></li>
<li><a class="reference internal" href="#storage-engines">Storage engines</a></li>
<li><a class="reference internal" href="#mysql-db-api-drivers">MySQL DB API Drivers</a><ul>
<li><a class="reference internal" href="#id6">mysqlclient</a></li>
<li><a class="reference internal" href="#id7">MySQL Connector/Python</a></li>
</ul>
</li>
<li><a class="reference internal" href="#time-zone-definitions">Time zone definitions</a></li>
<li><a class="reference internal" href="#creating-your-database">Creating your database</a><ul>
<li><a class="reference internal" href="#collation-settings">Collation settings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#connecting-to-the-database">Connecting to the database</a><ul>
<li><a class="reference internal" href="#setting-sql-mode">Setting <code class="docutils literal notranslate"><span class="pre">sql_mode</span></code></a></li>
<li><a class="reference internal" href="#mysql-isolation-level">Isolation level</a></li>
</ul>
</li>
<li><a class="reference internal" href="#creating-your-tables">Creating your tables</a></li>
<li><a class="reference internal" href="#table-names">Table names</a></li>
<li><a class="reference internal" href="#savepoints">Savepoints</a></li>
<li><a class="reference internal" href="#notes-on-specific-fields">Notes on specific fields</a><ul>
<li><a class="reference internal" href="#character-fields">Character fields</a></li>
<li><a class="reference internal" href="#textfield-limitations"><code class="docutils literal notranslate"><span class="pre">TextField</span></code> limitations</a></li>
<li><a class="reference internal" href="#fractional-seconds-support-for-time-and-datetime-fields">Fractional seconds support for Time and DateTime fields</a></li>
<li><a class="reference internal" href="#timestamp-columns"><code class="docutils literal notranslate"><span class="pre">TIMESTAMP</span></code> columns</a></li>
</ul>
</li>
<li><a class="reference internal" href="#row-locking-with-queryset-select-for-update">Row locking with <code class="docutils literal notranslate"><span class="pre">QuerySet.select_for_update()</span></code></a></li>
<li><a class="reference internal" href="#automatic-typecasting-can-cause-unexpected-results">Automatic typecasting can cause unexpected results</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sqlite-notes">SQLite notes</a><ul>
<li><a class="reference internal" href="#substring-matching-and-case-sensitivity">Substring matching and case sensitivity</a></li>
<li><a class="reference internal" href="#decimal-handling">Decimal handling</a></li>
<li><a class="reference internal" href="#database-is-locked-errors">“Database is locked” errors</a></li>
<li><a class="reference internal" href="#queryset-select-for-update-not-supported"><code class="docutils literal notranslate"><span class="pre">QuerySet.select_for_update()</span></code> not supported</a></li>
<li><a class="reference internal" href="#pyformat-parameter-style-in-raw-queries-not-supported">“pyformat” parameter style in raw queries not supported</a></li>
<li><a class="reference internal" href="#isolation-when-using-queryset-iterator">Isolation when using <code class="docutils literal notranslate"><span class="pre">QuerySet.iterator()</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#oracle-notes">Oracle notes</a><ul>
<li><a class="reference internal" href="#id12">Connecting to the database</a><ul>
<li><a class="reference internal" href="#full-dsn-and-easy-connect">Full DSN and Easy Connect</a></li>
</ul>
</li>
<li><a class="reference internal" href="#threaded-option">Threaded option</a></li>
<li><a class="reference internal" href="#insert-returning-into">INSERT … RETURNING INTO</a></li>
<li><a class="reference internal" href="#naming-issues">Naming issues</a></li>
<li><a class="reference internal" href="#null-and-empty-strings">NULL and empty strings</a></li>
<li><a class="reference internal" href="#id13"><code class="docutils literal notranslate"><span class="pre">TextField</span></code> limitations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-a-3rd-party-database-backend">Using a 3rd-party database backend</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="csrf.html"
                        title="previous chapter">Cross Site Request Forgery protection</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="django-admin.html"
                        title="next chapter"><code class="docutils literal notranslate"><span class="pre">django-admin</span></code> and <code class="docutils literal notranslate"><span class="pre">manage.py</span></code></a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/ref/databases.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Mar 04, 2020</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="csrf.html" title="Cross Site Request Forgery protection">previous</a>
     |
    <a href="index.html" title="API Reference" accesskey="U">up</a>
   |
    <a href="django-admin.html" title="&lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;django-admin&lt;/span&gt;&lt;/code&gt; and &lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;manage.py&lt;/span&gt;&lt;/code&gt;">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>